package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Member;
import cn.itcast.service.MemberService;
import cn.itcast.service.SMSService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.Map;

/**
 * 点击登入
 */
@RestController
@RequestMapping("member")
public class LoginController {
    @Autowired
    private SMSService smsService;

    @Reference
    private MemberService memberService;

    @PostMapping("login")
    public Result login(@RequestBody Map<String,String> loginInfo, HttpServletRequest request){
        String phone = loginInfo.get("phone");
        String validateCode = loginInfo.get("validateCode");

        HttpSession session = request.getSession();

        if (!smsService.checkCode(phone,validateCode)) {
            return new Result(false, MessageConstant.LOGIN_FAIL);
        }

        //根据手机号码查询该用户是否为会员
        Member member = memberService.findByTelephone(phone);
        if (null == member) {
            //不是会员,保存到会员表中
            member = new Member();
            member.setPhoneNumber(phone);
            member.setRegTime(new Date(System.currentTimeMillis()));
            memberService.add(member);
        }

        session.setAttribute("member",member);

        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
